package juc.producerandconsumer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 使用synchronize wait notify/notifyall
 * 实现单生产者单消费者模式
 */

 public class synchronize {
    public static AtomicInteger atomicInteger = new AtomicInteger();
    public volatile boolean flag = true;
    public static final int MAX_COUNT = 10;
    public static final List<Integer> pool = new ArrayList<>();

    public synchronized void produce() {
        // 判断，干活，通知
        while (flag) {
            // 每隔 1000 毫秒生产一个商品
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
                //池子满了，生产者停止生产
                while (pool.size() == MAX_COUNT) {
                    try {
                        System.out.println("pool is full, wating...");
                      wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //干活
                pool.add(atomicInteger.incrementAndGet());
                System.out.println(Thread.currentThread().getName()+"正在生产" + atomicInteger.get() +"号商品"+ "\t" + "当前商品数：" + pool.size());
                //通知
                notifyAll();
            }
        }


    public synchronized void consumue() {
        // 判断，干活，通知
        while (flag) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
                //没有商品，停止消费
                while (pool.size() == 0) {
                    try {
                        System.out.println("pool is empty, wating...");
                     wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //干活
                int temp = pool.get(0);
                pool.remove(0);
                System.out.println(Thread.currentThread().getName()+"正在消费" + temp +"号商品" +"\t" + "当前商品数：" + pool.size());
                //通知
               notifyAll();
            }
        }


    public void stop() {
        flag = false;
    }
}

class ProducerConsumer2 {

    public static void main(String[] args) {
        synchronize shareDataV2 = new synchronize();
        new Thread(() -> {
                shareDataV2.produce();
        }, "AAA").start();

        new Thread(() -> {
            shareDataV2.consumue();
        }, "BBB").start();

        new Thread(() -> {

                shareDataV2.produce();
        }, "CCC").start();

        new Thread(() -> {
            shareDataV2.consumue();
        }, "DDD").start();
    }
}
